<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/5/25
 * Time: 15:52
 * Mail:87658989@qq.com
 */

namespace app\base\service;

class Csv {
    private $file_path;
    private $f;
    private $fields;

    function open($fields) {
        $this->fields = $fields;
        $this->file_path = TEMP_PATH.time().mt_rand(0, 1000).".csv";
        $this->f = fopen($this->file_path, 'wb');
        $titles = "";

        foreach ($this->fields as $k=>$v) {
            if (strlen($titles) > 0)
                $titles .= ",";
            $titles .= $v;
        }
        $titles = mb_convert_encoding($titles . "\n", "gbk", "UTF-8");
        fwrite($this->f, $titles);
    }

    function writeAll($list) {
        foreach ($list as $obj) {
            $this->write($obj);
        }
    }

    function write($obj) {
        $content = "";
        foreach ($this->fields as $k=>$v) {
            if (strlen($content) > 0)
                $content .= ",";
            $out = $obj[$k];
            if($out>1000000) $out = "\t".$out;
            $content .= str_replace(",", "，", $out);
        }
        $content = mb_convert_encoding($content . "\n", "gbk", "UTF-8");
        fwrite($this->f, $content);
    }

    function close() {
        fclose($this->f);
        Http::download($this->file_path);
        unlink($this->file_path);
    }

    //////////////////////分割线，以下是我修改的//////////////////////

    //关闭之后，返回当前文件名
    function myClose(){
        fclose($this->f);
        return $this->file_path;
    }

    //合并文件，并生成下载文件，然后调用下载
    //@param			$files			需要合并的文件数组
    //@param			$trimNL			是否清楚空行换行，默认为true
    function mergeCsvToDownload($files,$trimNL=true){
        $exportFile=TEMP_PATH.'export_'.time().mt_rand(0, 1000).".csv";
        $exportArr=array();
        foreach ($files as $index=>$file){
            $content=file_get_contents($file);
            $arr=explode("\n", $content);
            if($index==0){
                $exportArr=$arr;
            }else{
                //删除第一行
                unset($arr[0]);
                $exportArr=array_merge($exportArr,$arr);
            }
            unlink($file);
        }

        if($trimNL){
            foreach ($exportArr as $k=>&$v){
                if(!$v) unset($exportArr[$k]);//清楚空元素
            }
        }

        $content=implode("\n", $exportArr);
        file_put_contents($exportFile, $content);
        Http::download($exportFile);
    }
}